<?php 
/**
 * 
 * 把传入的unicode编码转换成对应的utf8字符
 * @param int $unicode
 * @return String
 */
function unicode2Utf8 ($unicode){
		
	$utf8Str = '';
	if($unicode <= 0x7f){
		//单字节utf-8字符
		$tpl = 0x0;
		$mask = 0x7f;
		$u1= $tpl | ($unicode & $mask);
		$utf8Str = pack('c',$u1);
	}elseif($unicode > 0x7f && $unicode <= 0x7ff){
		//双字节utf-8字符
		$tpl = 0xc0;
		$mask = 0x7c0;
		$u1 = $tpl | (($unicode & $mask)>>6);
    	$tpl = 0x80;
		$mask = 0x3f;
		$u2 = $tpl | ($unicode & $mask);
			
		$utf8Str = pack('c2',$u1,$u2);
		
		
	}elseif($unicode > 0x7ff && $unicode <= 0xffff){
		//三字节utf-8字符
		$tpl = 0xe0;
		$mask = 0xf000;
		$u1 = $tpl | (($unicode & $mask)>>12);
			
		$tpl = 0x80;
		$mask = 0xfc0;
		$u2 = $tpl | (($unicode & $mask)>>6);
	
		$tpl = 0x80;
		$mask = 0x3f;
		$u3 = $tpl | ($unicode & $mask);
    	$utf8Str = pack('c3',$u1,$u2,$u3);
    
	
	}elseif($unicode > 0xffff && $unicode <= 0x10ffff){
		//四字节utf-8字符 <一般不会有>
		exit;
		$tpl = 0xf0;
		$mask = 0x1c0000;
		$u1 = $tpl | (($unicode & $mask)>>18);
		
		$tpl = 0x80;
		$mask = 0x3f000;
		$u2 = $tpl | (($unicode & $mask)>>12);
		
		$tpl = 0x80;
		$mask = 0xfc0;
		$u3 = $tpl | (($unicode & $mask)>>6);
		
		$tpl = 0x80;
		$mask = 0x3f;
		$u4 = $tpl | ($unicode & $mask);
    	$utf8Str = pack('c4',$u1,$u2,$u3,$u4);
		
	}
	
	
	return $utf8Str;

}
/**
 * 
 * 截取utf8编码的字符串
 * @param unknown_type $str
 * @param unknown_type $limit
 */
function  utf8_substr($str,$limit){
	
	$count = 0;
	$start = 0;
	$len = strlen($str);


	$re = '';
	
	while(($start < $len) && ($count < $limit)){
		
		$ord = ord($str[$start]);
		 
		if($ord <= 0x7f){
			$re .= $str[$start];
		    $start++;
		  $count +=1;
		    			
		}elseif($ord >=0xc0 && $ord <=0xdf){
						
			$re .= $str[$start]. $str[$start+1];
			$start += 2;
			$count +=2; //一个双字节字符当2个长度处理
		}elseif($ord >=0xe0 && $ord <=0xef){
									
			$re .= $str[$start].$str[$start+1].$str[$start+2];
			$start += 3;
			$count +=2;//一个3字节字符当2个长度处理
		}else{
			$start++;
		}
		
	}
		
	
	
	return $re;
}
?>